//
//  FlowDetailVC.swift
//  Employee
//
//  Created by swordjoy on 2017/6/28.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Moya

enum FlowDetailVCType {
  case home
  case apply
  case check
  case copy
}

class FlowDetailVC: BaseVC {
  var type: FlowDetailVCType!
  var flowId: String!
  var refreshBefore: VoidClosure?
  
  fileprivate var model: ApplyDetail?
  
  fileprivate var tableView: UITableView!
  fileprivate var lineView: UIView!
  fileprivate var containerView: UIView!
  fileprivate var allowButton: UIButton!
  fileprivate var passButton: UIButton!
  fileprivate var cancle: Cancellable!
  fileprivate var removeContainerView: UIView!
  fileprivate var removeButton: UIButton!
  fileprivate var footerView: UIView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    create()
    pullData()
  }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        GlobalConfig.baiduStatisticsPageViewStart("流程详情")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalConfig.baiduStatisticsPageViewEnd("流程详情")
    }
    
}

// MARK: -  action

extension FlowDetailVC {
  
  @objc fileprivate func removeAction() {
    let finishPop = TipPopV(frame: UIScreen.main.bounds, type: .flow)
    finishPop.show(in: self.navigationController!.view)
    
    finishPop.confirmClosure = { [unowned self] in
      guard let temp = self.flowId else { return }
      
      let _ = FlowRequest.shared.removeFlow(id: temp, success: { 
        SJHint.show("操作成功")
        self.pullData()
        self.refreshBefore?()
      }, failure: nil)
    }
  }
  
  @objc fileprivate func allowAction() {
    let vc = FlowCheckVC()
    vc.isAllow = true
    vc.flowId = flowId
    vc.refreshBefore = {
      self.pullData()
      self.refreshBefore?()
    }
    navigationController?.pushViewController(vc, animated: true)
  }
  
  @objc fileprivate func passAction() {
    let vc = FlowCheckVC()
    vc.isAllow = false
    vc.flowId = flowId
    vc.refreshBefore = {
      self.pullData()
      self.refreshBefore?()
    }
    navigationController?.pushViewController(vc, animated: true)
  }
}

// MARK: - UITableViewDelegate

extension FlowDetailVC: UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if 0 == indexPath.section {
      let title = model?.title ?? ""
      return OrderTitleCell.heightWithTitle(title: title)
    }
    else if 1 == indexPath.section {
      let temp = model?.result[indexPath.row].style ?? ""
      if "DateRange" == temp { return 150 }
      else {
        guard let temp = model?.result[indexPath.row] else { return 0 }
        return InspectionDetailCell.height(with: temp)
      }
    }
    else if 2 == indexPath.section {
      guard let temps = model?.images else { return 0 }
      if temps.isEmpty { return 0 }
        if temps.count <= 4 { return (UIScreen.width - 80) / 4 + 90 }
        else { return (UIScreen.width - 80) / 2 + 90 }
    }
    else {
      return CheckCommentCell.height(with: model?.people[indexPath.row].approverExplain ?? "")
    }
  }
  
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offSetY = scrollView.contentOffset.y
    if offSetY > 70 { title = model?.title }
    else { title = "" }
  }
  
}

// MARK: - UITableViewDataSource

extension FlowDetailVC: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 4
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if 0 == section { return 1 }
    else if 1 == section { return model?.result.count ?? 0 }
    else if 2 == section { return 1 }
    else { return model?.people.count ?? 0 }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if 0 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: OrderTitleCell.identifier) as! OrderTitleCell
      cell.flowModel = model
      return cell
    }
    else if 1 == indexPath.section {
      guard let temp = model?.result[indexPath.row] else { return UITableViewCell() }
      // 日期区间
      if "DateRange" == temp.style {
        let cell = tableView.dequeueReusableCell(withIdentifier: DateRangeFormCell.identifier) as! DateRangeFormCell
        cell.isDetail = true
        cell.detailModel = temp
        return cell
      }
        // 其他
      else {
        let cell = tableView.dequeueReusableCell(withIdentifier: InspectionDetailCell.identifier) as! InspectionDetailCell
        cell.isFlow = true
        cell.model = temp
        cell.isDetail = true
        return cell
      }
    }
    else if 2 == indexPath.section {
      let cell = tableView.dequeueReusableCell(withIdentifier: ImageShowCell.identifier) as! ImageShowCell
      cell.models = model?.imageUrlStrings ?? []
      cell.cellDidClick = { [unowned self] (index, collectionView) in
        guard let temps = self.model?.images else {
            return
        }
        
        var images: [SJImageModel] = []
        for (index, item) in temps.enumerated() {
            if let cell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? ImageSelectCell {
                let image = SJImageModel(thumb: cell.imageV, thumb: cell.imageV.image, original: item.filePath)
                images.append(image)
            }
            else {
                let image = SJImageModel(thumb: nil, thumb: nil, original: item.filePath)
                images.append(image)
            }
        }
        
        let viewer = ImageViewer(images: images, presentingVC: self)
        viewer.show(index: index)
        
      }
      return cell
    }
    else {
      guard let temp = model else { return UITableViewCell() }
      var tempModel = temp.people[indexPath.row]
      let cell = tableView.dequeueReusableCell(withIdentifier: CheckCommentCell.identifier) as! CheckCommentCell
      if 0 == indexPath.row { cell.isFirst = true }
      else { cell.isFirst = false }
      if temp.sortId == tempModel.flowSortId { tempModel.isCheck = true }
      cell.model = tempModel
      return cell
    }
  }
}

// MARK: - fileprivate

extension FlowDetailVC {
  
  fileprivate func pullData() {
    guard let temp = flowId else {
      SJHint.show("详情不存在")
      return
    }
    
    SJApp.showHUD()
    cancle = FlowRequest.shared.getApplyDetail(id: temp, success: { (data) in
      self.model = data
      runOnMainThread {
        if nil == self.tableView.superview { self.view.addSubview(self.tableView) }
        
        if data.approvaled && (.check == self.type || .home == self.type ) {
          self.containerView.isHidden = false
          self.tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight - 50)
        }
        else {
          self.containerView.isHidden = true
          self.tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight)
        }
        
        if data.withdrawed && .apply == self.type { self.tableView.tableFooterView = self.removeContainerView }
        else { self.tableView.tableFooterView = self.footerView }
        
       self.tableView.reloadData()
      }
    }, failure: { 
      SJHint.show("获取详情信息失败")
    })
  }
  
  fileprivate func create() {
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "申请详情"
    addBackItem()
    
    tableView = UITableView()
    self.tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight)
    tableView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.register(OrderTitleCell.self, forCellReuseIdentifier: OrderTitleCell.identifier)
    tableView.register(DateRangeFormCell.self, forCellReuseIdentifier: DateRangeFormCell.identifier)
    tableView.register(InspectionDetailCell.self, forCellReuseIdentifier: InspectionDetailCell.identifier)
    tableView.register(ImageShowCell.self, forCellReuseIdentifier: ImageShowCell.identifier)
    tableView.register(CheckCommentCell.self, forCellReuseIdentifier: CheckCommentCell.identifier)
    
    footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    
    containerView = UIView()
    view.addSubview(containerView)
    containerView.backgroundColor = UIColor.white
    containerView.snp.makeConstraints { (make) in
      make.left.right.bottom.equalToSuperview()
      make.height.equalTo(50)
    }
    containerView.isHidden = true
    
    lineView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 1))
    lineView.backgroundColor = GlobalConfig.BGWhiteColor
    containerView.addSubview(lineView)
    
    allowButton = UIButton()
    containerView.addSubview(allowButton)
    allowButton.setTitle("通过", for: .normal)
    allowButton.backgroundColor = GlobalConfig.BGSkyBlueColor
    allowButton.setTitleColor(UIColor.white, for: .normal)
    allowButton.titleLabel?.font = GlobalConfig.system14Font
    allowButton.addTarget(self, action: #selector(allowAction), for: .touchUpInside)
    allowButton.snp.makeConstraints { (make) in
      make.left.equalTo(10)
      make.top.equalTo(5)
      make.bottom.equalTo(-5)
      make.width.equalTo((UIScreen.width - 30) / 2)
    }
    allowButton.layer.cornerRadius = 2
    allowButton.clipsToBounds = true
    
    passButton = UIButton()
    containerView.addSubview(passButton)
    passButton.setTitle("不通过", for: .normal)
    passButton.backgroundColor = GlobalConfig.BGSkyBlueColor
    passButton.setTitleColor(UIColor.white, for: .normal)
    passButton.titleLabel?.font = GlobalConfig.system14Font
    passButton.addTarget(self, action: #selector(passAction), for: .touchUpInside)
    passButton.snp.makeConstraints { (make) in
      make.right.equalTo(-10)
      make.top.equalTo(5)
      make.bottom.equalTo(-5)
      make.width.equalTo((UIScreen.width - 30) / 2)
    }
    passButton.layer.cornerRadius = 2
    passButton.clipsToBounds = true
    
    removeContainerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 70))
    removeContainerView.backgroundColor = GlobalConfig.BGWhiteColor

    removeButton = UIButton(frame: CGRect(x: 10, y: 10, width: UIScreen.width - 20, height: 50))
    removeButton.backgroundColor = UIColor.white
    removeContainerView.addSubview(removeButton)
    removeButton.setTitle("撤销该流程", for: .normal)
    removeButton.setTitleColor(GlobalConfig.GrapeFruitColor, for: .normal)
    removeButton.titleLabel?.font = GlobalConfig.system16Font
    removeButton.layer.cornerRadius = 2
    removeButton.addTarget(self, action: #selector(removeAction), for: .touchUpInside)
    removeButton.clipsToBounds = true
  }
  
}
